// pages/entry/index.js
import { getUseCoupon } from '../../api/coupon.js'
import { setCalculate,createOrder,orderpay,queryOrder} from '../../api/order.js'
import { getUserInfo } from '../../api/user.js'
import { removeObj } from '../../utils/removeObj.js'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    integralPrice:0,//积分的金额
    showgroupdata:false,//组别遮罩层显示状态
    userindex:0,//查询信息确认遮罩层的下标
    showInformationValidation: false,//是否信息确认遮罩层
      agreement:'',//条款
      save:0,//节约了多少钱
      orderSn:'',//
      // nowjifen:0,//当前积分
      coupon:'',//优惠券
      jifen:false,//是否使用积分
      Clausestate:false,//是否本人已阅读且同意《xx条款》所述内容
      couponlength:0,//有多少张优惠券可以用
      totalPrice:0,//总价格
      actualPrice:0,//实际需要支付金额
      select:-1,
      Integral:[
        {
          title:''
        }
      ]
  },
  //组别弹窗层显示隐藏
  showview() {
    this.setData({ showgroupdata: !this.data.showgroupdata })
  },
  showInformation(e) {
    let { showInformationValidation, matchSkuList, select } = this.data
    let { index, close } = e.currentTarget.dataset
    this.setData({ showInformationValidation: !showInformationValidation, userindex: index})
    if (index != null) {
      this.setData({ userindex: index })
    }
  },
  showModel(e){
    this.setData({ showInformationValidation: e.detail})
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app._getSettingInfo(res=>{
      this.setData({agreement:res.agreement})
    })
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    let data = prevPage.data;
    this.setData(removeObj(data, ['navShowMore','navList', 'current', 'lists', 'isRequest', 'bindIndex','showviewstate'])) //取上页data里的数据也可以修改
  },
  //是否本人已阅读
  checkboxChange: function (e) {
    this.setData({Clausestate: e.detail.value.length > 0})
  },
  //条款详情 agreementDetail
  agreementDetail(){
      wx.navigateTo({
        url: '/pages/agreement_detail/index',
      })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //是否有积分可使用
    // this._getUserInfo()
    // let data = wx.getStorageSync('data')//组别
    // let selectedUser = wx.getStorageSync('selectedUser')//参赛人员
    // let coupon = wx.getStorageSync('coupon')//优惠券
    // if(data){
    //    data = JSON.parse(data)
    //   this.setData({group:data})
    // }
    // if(selectedUser){
    //   this.setData({users:JSON.parse(selectedUser)})
    // }
    // if(coupon){
    //   this.setData({coupon:JSON.parse(coupon)})
    // }else{
    //   this.setData({coupon:''})
    // }
    // //已经选择了参赛人员再去计算价格
    // if(this.data.users.length>0){
    //计算订单价格（第一步）
    this._setCalculate()
    // }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //组别遮罩层显示隐藏
  showgroupdata(){
    this.setData({showgroupdata:!this.data.showgroupdata})
  },
  delete(e){
    let oldid = e.currentTarget.dataset.participantid
    let selectedUser = wx.getStorageSync('selectedUser')//参赛人员
    selectedUser = JSON.parse(selectedUser)
    // selectedUser.forEach((item,i) => {
    //   if(item.participantId==oldid){
    //     item.splice(i, 1);
    //   }
    // });
    for (var i = 0; i < selectedUser.length; i++) {
    　　if(selectedUser[i].participantId==oldid){
            selectedUser.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
    　　　　i--; // 如果不减，将漏掉一个元素
    　　}
    }
    this.setData({users:selectedUser})
    wx.setStorageSync('selectedUser', JSON.stringify(selectedUser))
    if(selectedUser.length<1){
      wx.removeStorageSync('coupon')
      this.setData({
        coupon:''
      })
    }
    //删除完之后在计算订单，再获取优惠券
    this._setCalculate()
  },
  // choose(e){
  //   let index = e.currentTarget.dataset.index
  //   this.setData({ select: e.currentTarget.dataset.index != this.data.select ? e.currentTarget.dataset.index:-1})
  // },
  add(){
      wx.navigateTo({
        url: '/pages/participant/index?skuId=' + this.data.group.skuId,
      })
  },
  switch2Change(e){
    let {matchSkuList,select} = this.data
    if(e.currentTarget.dataset.checked==true){
      this.setData({jifen:false})
    }else{
      this.setData({jifen:true})
    }
     if(matchSkuList[select].selectedUser.length>0){
      //计算订单价格（第一步）
      this._setCalculate()
     }
  },
  //跳转到优惠券列表
  skipcoupon(){
    //有可用优惠券的时候才跳转到优惠券列表
    let { couponlength, matchSkuList,select, totalPrice } = this.data
    if(couponlength>0){
      wx.navigateTo({
        url: '/pages/coupon/index?matchid='+matchSkuList[select].matchId+'&actualprice='+totalPrice,
      })
    }
  },
  //获取可使用优惠券张数
  _getUseCouponCount(){
    let { matchSkuList,totalPrice,select} = this.data
    if(matchSkuList[select].selectedUser.length>0){
      getUseCoupon(matchSkuList[select].matchId,totalPrice).then(res=>{
        if(res.data){
          this.setData({
            couponlength:res.data.length
          })
        }
      })
    }
  },
  // 计算订单价格（第一步） 
  _setCalculate(){
    let { coupon, jifen, matchSkuList, select, groupValue} = this.data
    let that = this
    let couponstate = coupon!=null && coupon!=''//是否使用优惠券
    let couponId = couponstate==true?coupon.couponId:''
    // let participantId = users.length>0?users[0].participantId:''
    let participantId = []
    let matchSku = matchSkuList[select] //组别信息
    let users = matchSku.selectedUser//组别下的用户
    if(users.length>0){
      users.forEach((item,i) => {
        participantId.push(item.participantId)
      });
    }else{
      participantId = ''
    }
    let applyList = []
    users.forEach(e => {
      applyList.push({ participantId: e.participantId, qualificateId: matchSku.qulificateIds, images:e.arr||[]})
    })
    // console.log(applyList)
    let formMapStrArray=""
    let user = matchSku.selectedUser;
    if (user && matchSku.matchSkuFormList.length>0){
      formMapStrArray="{"
      user.forEach((e,i) => {

        formMapStrArray+=`"${e.participantId}":${JSON.stringify(e.matchFormList||matchSku.matchSkuFormList)},`;


        if(i==user.length-1){
          formMapStrArray=formMapStrArray!='{'?formMapStrArray.substr(0,formMapStrArray.length-1)+'}':''
        }
      });
    }
    applyList.forEach(e=>{
      let newImg = ''
      e.images.forEach((ev,i)=>{
        newImg += ev + (i < e.images.length-1 ? ',' : '')
      })
      e.images = newImg 
    })
    let obj={
      useIntegral:jifen,//是否使用积分
      useCoupon:couponstate,//是否使用优惠券
      matchId:matchSku.matchId,//赛事主键
      skuId:matchSku.skuId,//赛事套餐主键
      participantIds:participantId,//参赛者信息主键
      applyStr: JSON.stringify(applyList),
      formMapStr:formMapStrArray
    }
    if (couponId!='') {
      obj.userCouponId = couponId//优惠券主键
    }
    if (matchSkuList[select].skuType == 2){
      obj.groupName = groupValue
    }
    setCalculate(obj).then(res=>{
      // 节约了多少
      if (res.data) {
        this.setData({
          save: res.data.savePrice,
          actualPrice: res.data.actualPrice,
          totalPrice: res.data.totalPrice,
          integralPrice: res.data.integralPrice//积分的金额
        })
        if (this.data.couponlength < 1) {
          //查看优惠券列表
          this._getUseCouponCount()
        }
      }
    })
  },
   // 创建订单（第二步） 
   _createOrder(){
     let { coupon, matchSkuList, select, jifen, groupValue} = this.data
     let couponstate = coupon!=null && coupon!=''//是否使用优惠券
     let couponId = couponstate==true?coupon.couponId:''
    let participantId = []
    let users = matchSkuList[select].selectedUser
    if(users.length>0){
      users.forEach((item,i) => {
        participantId.push(item.participantId)
      });
    }else{
      participantId = ''
    }
    let applyList = []
    users.forEach(e => {
        let applyobj={}
        applyobj.participantId=e.participantId
        applyobj.qualificateId=matchSkuList[select].qulificateIds
        applyobj.images=e.arr?e.arr:[]
        applyList.push(applyobj)
    })
    let formMapStrArray=""
    let user = matchSkuList[select].selectedUser;
     if (user && matchSkuList[select].matchSkuFormList.length>0){
      formMapStrArray="{"
      user.forEach((e,i) => {
        formMapStrArray+=`"${e.participantId}":${JSON.stringify(e.matchFormList||matchSkuList[select].matchSkuFormList)},`;
        if(i==user.length-1){
          formMapStrArray=formMapStrArray!='{'?formMapStrArray.substr(0,formMapStrArray.length-1)+'}':''
        }
      });
    }
     applyList.forEach(e => {
       let newImg = ''
       e.images.forEach((ev, i) => {
         newImg += ev + (i < e.images.length - 1 ? ',' : '')
       })
       e.images = newImg
     })
    let obj={
      useIntegral:jifen,//是否使用积分
      useCoupon:couponstate,//是否使用优惠券
      userCouponId:couponId,//优惠券主键
      matchId:matchSkuList[select].matchId,//赛事主键
      skuId:matchSkuList[select].skuId,//赛事套餐主键
      participantIds:participantId,//参赛者信息主键
      applyStr: JSON.stringify(applyList),
      formMapStr:formMapStrArray
     }
     if (matchSkuList[select].skuType == 2) {
       obj.groupName = groupValue
     }
    createOrder(obj).then(res=>{
      console.log(res)
      if (res.code == 0) {
        this.setData({orderSn: res.data.orderSn})
        this._orderpay(res.data.orderSn)
      }
    })
  },
  //调起官方微信支付接口
  Payment(result){
    let that = this
    wx.requestPayment({
      timeStamp: result.timeStamp,
      nonceStr: result.nonceStr,
      package: result.packageValue,
      signType: result.signType,
      paySign:  result.paySign,
      success (res) { 
          wx.removeStorageSync("data")
          wx.removeStorageSync("selectedUser")
          wx.removeStorageSync("coupon")
          //主动查询订单支付状态（第四步）
          that._queryOrder()
      },
      fail (res) { 
        wx.navigateTo({
          url: '/pages/order/index',
        })
      }
    })
  },
   //主动查询订单支付状态（第四步）
  _queryOrder(){
    queryOrder(this.data.orderSn).then(res=>{
      if(res.data.msg=="OK"){
        wx.showModal({
          title: '支付成功',
          content: '请注意时间合理安排',
          cancelText:'返回首页',
          confirmText:'查看订单',
          confirmColor:'#576B95',
          success (resx) {
            if (resx.confirm) {
              wx.redirectTo({
                url: '/pages/order-new-detail/index?orderid='+res.data.orderId,
              })
            } else if (resx.cancel) {
              wx.switchTab({
                url: '/pages/index/index',
              })
            }
          }
        })
      }
  })
  },
  //调起官方微信支付接口
  _orderpay(orderSn){
    orderpay(orderSn).then(res=>{
      if(res.data.needPay){
        this.Payment(res.data.result)
      }else{
          //主动查询订单支付状态（第四步）
          this._queryOrder()
      }
    })
  },
  //去支付
  gopay(){
    let { Clausestate, matchSkuList,select, orderSn, agreement} = this.data
    if(Clausestate==true){
      let users = matchSkuList[select].selectedUser
      if(users.length>0){
          this._createOrder()
      }else{
        wx.showToast({
          title: '请选择参赛人员',
          icon:'none'
        })
      }
    }else{
      wx.showToast({
        title: '请阅读且同意《' + agreement+'》所述内容',
        icon:'none'
      })
    }
  }
})